package com.lang.generator.core.helper;

import cn.hutool.core.collection.CollectionUtil;
import com.lang.generator.core.sql.generator.DataGenerator;
import com.lang.generator.core.sql.generator.DataGeneratorFactory;
import com.lang.generator.domain.entity.TableField;
import com.lang.generator.domain.entity.TableStructure;
import com.lang.generator.domain.enums.MockTypeEnum;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 模拟数据助手
 *
 * @author zhangren
 * @date 2022/12/12
 */
@Component
public class MockDataHelper {

    /**
     * 模拟数据生成
     * @param tableSchema
     * @param rowNum
     * @return
     */
    public List<Map<String, Object>> generateMockData(TableStructure tableSchema, int rowNum) {
        List<TableField> fieldList = tableSchema.getTableFields();
        // 初始化结果数据
        List<Map<String, Object>> resultList = new ArrayList<>(rowNum);
        for (int i = 0; i < rowNum; i++) {
            resultList.add(new HashMap<>(rowNum));
        }


        // 依次生成每一列
        for (TableField field : fieldList) {
            MockTypeEnum mockTypeEnum = Optional.ofNullable(MockTypeEnum.getEnumByValue(field.getMockType()))
                    .orElse(MockTypeEnum.NONE);
            DataGenerator dataGenerator = DataGeneratorFactory.getGenerator(mockTypeEnum);
            List<String> mockDataList = dataGenerator.doGenerate(field, rowNum);
            String fieldName = field.getFieldName();
            // 填充结果列表
            if (CollectionUtil.isNotEmpty(mockDataList)) {
                for (int i = 0; i < rowNum; i++) {
                    resultList.get(i).put(fieldName, mockDataList.get(i));
                }
            }
        }
        return resultList;
    }

}
